import {
	doubleValidate,
	validatePhone,
	isInt,
	mapVerification
} from "~/utils/validate.js";
import {
	underconstructionAdd,
	underconstructionEdit,
	getUnderconstruction,
	validateprojectCode,
	initMilestones,
	validateProject
} from "../api/construction";
import { mapGetters, mapState } from "vuex";
import { delFiles, checkFiles } from "@/api/operate-construction-contract";
import positionDialog from "@/components/positionDialog";
import BaseLoad from "@/assets/vue-mixin/BaseLoad";
import {
	validateFacRoomName,
	validateProjectCountryCode
} from "~/views/property-info-sys/project-manage/api/project_manage";
import { validateLandCode } from "@/views/property-plan-sys/property-plan-manage/planning-property/api/planning.js";
import moment from "moment";
import vPdf from "@/components/v-pdf";
import { download } from "@/admin/api/common";
import { downloadBlob } from "@/utils";
export default {
	name: "project-construction",
	components: { positionDialog, vPdf },
	data() {
		var validateprojectAddr = (rule, value, callback) => {
			if (value === "" || value === null || value === undefined) {
				callback(new Error("请输入项目地址！"));
				this.formPlanning.projectAddr = "";
			} else if (value.length > 30) {
				callback(new Error("长度在0-30个字符串！"));
				this.formPlanning.projectAddr = "";
			} else {
				// 借助propertyBasic对象进行检验，通过后赋值
				this.formPlanning.projectAddr = this.formPlanning.propertyBasic.projectAddr;
				callback();
			}
		};
		let floorNumValidator = (rule, value, callback) => {
			const re = /^-?[1-9]\d*$/;
			const rsCheck = re.test(value);
			if (!rsCheck) {
				callback(new Error("请输入-20 至 200之间非0的整数"));
			} else {
				if (value > 200) {
					return callback(new Error("最大值不超过200"));
				} else if (value < -20) {
					return callback(new Error("最小值不能小于-20"));
				} else {
					callback();
				}
			}
		};
		return {
			// hxf-0828-项目信息
			formPlanning: {
				// hxf-0901-项目信息
				propertyBasic: {
					projectId: "",
					projectCode: "",
					projectName: "",
					projectCountryCode: "",
					projectArea: "",
					projectType: "",
					projectStreet: "",
					isUpdate: "2",
					stage: ""
				},
				/*// hxf-0901-项目信息-项目地址
                projectAddr: '',*/
				// hxf-0901-配套信息
				supportingFacilities: [],
				// hxf-0910-资料信息
				projectMilestones: [],
				landInfo: {
					address: "",
					addressInfo: "",
					cityCode: "",
					community: "",
					countyCode: "",
					manageUnit: "",
					landContractNum: "",
					landId: "",
					landUse: "",
					parcelArea: "",
					parcelNum: "",
					remarks: "",
					street: "",
					areaCode: "",
					areaName: ""
				}
			},
			// hxf-0929-土地信息校验
			landInfo_rules: {
				parcelNum: [
					{ required: true, message: "请输入宗地号", trigger: "blur" },
					{ min: 0, max: 30, message: "长度在0-30个字符串", trigger: "blur" }
				],
				parcelArea: [
					{ required: true, message: "请输入宗地面积(m²)", trigger: "blur" },
					{ validator: doubleValidate, trigger: "blur" }
				],
				landUse: [
					{ required: true, message: "请选择土地用途", trigger: "blur" }
				],
				/*landContractNum: [
                    {required: true, message: "请输入土地合同号", trigger: "blur"}
                ],*/
				cityCode: [
					{
						required: true,
						validator: (rules, value, callback) => {
							//区县
							let county = this.formPlanning.landInfo.countyCode;
							//   街道
							let street = this.formPlanning.landInfo.street;
							//   社区
							let community = this.formPlanning.landInfo.community;
							//   管理所
							let addressInfo = this.formPlanning.landInfo.addressInfo;
							if (!value || !county || !street || !community || !addressInfo) {
								return callback(new Error("物业地址不能为空"));
							}
							return callback();
						},
						trigger: "blur"
					}
				],
				addressInfo: [
					{ required: true, message: "地址不能为空", trigger: "blur" },
					{ min: 0, max: 50, message: "长度在0-50个字符串", trigger: "blur" }
				]
			},
			// hxf-0831-项目信息校验
			propertyBasic_rules: {
				// projectCode: [
				//     { required: true, message: "请输入项目编号", trigger: "blur" },
				//     { min: 0, max: 30, message: "长度在0-30个字符串", trigger: "blur" },
				//     { validator: validateprojectCode, trigger: "change" },
				// ],
				projectName: [
					{ required: true, message: "请输入项目名称", trigger: "blur" },
					{ min: 0, max: 30, message: "长度在0-30个字符串", trigger: "blur" }
				],
				projectArea: [
					{ required: true, message: "请输入项目面积", trigger: "blur" },
					{ validator: doubleValidate, trigger: "blur" }
				],
				contactPhone: [
					{ required: false },
					{ validator: validatePhone, trigger: "blur" }
				],
				mapCoordinates: [
					{ required: true, message: "请输入地图坐标", trigger: "blur" },
					{ min: 0, max: 50, message: "长度在0-50个字符串", trigger: "blur" },
					{ validator: mapVerification, trigger: "blur" }
				],
				projectCountryCode: [
					{ required: true, message: "请输入项目国家编号", trigger: "blur" },
					{ min: 0, max: 100, message: "长度在0-100个字符串", trigger: "blur" }
				],
				projectType: [
					{ required: true, message: "请输入项目类型", trigger: "blur" },
					{ min: 0, max: 30, message: "长度在0-30个字符串", trigger: "blur" }
				] /*,
                projectStreet: [
                    { required: true, message: "请输入项目街道", trigger: "blur" },
                    { min: 0, max: 30, message: "长度在0-30个字符串", trigger: "blur" },
                ],
                stage: [
                    { required: true, message: "请输入当前阶段", trigger: "blur" },
                    { min: 0, max: 30, message: "长度在0-30个字符串", trigger: "blur" },
                ],
                projectAddr: [{ validator: validateprojectAddr, trigger: 'blur' }]*/
			},
			// hxf-0831-配套信息校验
			/* supportingFacilities_rules: {
                realtyName: [
                    { required: true, message: "请输入物业名称", trigger: "blur" },
                    { min: 0, max: 30, message: "长度在0-30个字符串", trigger: "blur" },
                ],
                projectType: [
                    { required: true, message: "请输入项目类型", trigger: "blur" },
                    { min: 0, max: 30, message: "长度在0-30个字符串", trigger: "blur" },
                ],
                projectSubclassType: [
                    { required: true, message: "请输入项目小类", trigger: "blur" },
                    { min: 0, max: 30, message: "长度在0-30个字符串", trigger: "blur" },
                ],
                floorSpace: [
                    { required: true, message: "请输入占地面积", trigger: "blur" },
                    { validator: doubleValidate, trigger: "change" },
                ],
                floorArea: [
                    { required: true, message: "请输入建筑面积", trigger: "blur" },
                    { validator: doubleValidate, trigger: "change" },
                ],
                transferMode: [
                    { required: true, message: "请输入移交方式", trigger: "blur" },
                    { min: 0, max: 30, message: "长度在0-30个字符串", trigger: "blur" },
                ]
            },*/
			// hxf-0929-配套信息校验
			bulletInformation_rules: {
				buildingName: [
					{ required: true, message: "请输入楼栋名称", trigger: "blur" },
					{ min: 0, max: 25, message: "长度在0-25个字符串", trigger: "blur" }
				],
				floorNum: [
					{ required: true, message: "请输入楼层", trigger: "blur" },
					{ validator: floorNumValidator, trigger: "blur" }
				],
				propertyName: [
					{ required: true, message: "请输入物业名称", trigger: "blur" },
					{ min: 0, max: 30, message: "长度在0-30个字符串", trigger: "blur" }
				],
				usedName: [
					{ required: false, message: "请输入曾用名", trigger: "blur" },
					{ min: 0, max: 30, message: "长度在0-30个字符串", trigger: "blur" }
				],
				address: [
					{ required: true, message: "请输入物业地址", trigger: "blur" },
					{ min: 0, max: 50, message: "长度在0-50个字符串", trigger: "blur" }
				],
				initialType: [
					{ required: true, message: "请选择初始类别", trigger: "blur" }
				],
				planUse: [
					{ required: true, message: "请选择规划用途", trigger: "blur" },
					{ min: 0, max: 30, message: "长度在0-30个字符串", trigger: "blur" }
				],
				parkingSpotNum: [
					{ required: false, message: "请输入停车位数", trigger: "blur" },
					{ validator: isInt, trigger: "blur" }
				],
				totalBuildings: [
					{ required: true, message: "请输入总栋数", trigger: "blur" },
					{ validator: isInt, trigger: "blur" }
				],
				useLandArea: [
					{ required: true, message: "请输入用地面积", trigger: "blur" },
					{ validator: doubleValidate, trigger: "blur" }
				],
				floorSpace: [
					{ required: false, message: "请输入占地面积", trigger: "blur" },
					{ validator: doubleValidate, trigger: "blur" }
				],
				buildArea: [
					{ required: false, message: "请输入建筑面积", trigger: "blur" },
					{ validator: doubleValidate, trigger: "blur" }
				],
				insideArea: [
					{ required: false, message: "请输入套内面积", trigger: "blur" },
					{ validator: doubleValidate, trigger: "blur" }
				],
				operation: [
					{ required: true, message: "请选择经营类型", trigger: "blur" }
				],
				useArea: [
					{ required: false, message: "请输入使用面积", trigger: "blur" },
					{ validator: doubleValidate, trigger: "blur" }
				],
				unmanagedArea: [
					{ required: false, message: "请输入非经营面积", trigger: "blur" },
					{ validator: doubleValidate, trigger: "blur" }
				],
				managedArea: [
					{ required: false, message: "请输入经营面积", trigger: "blur" },
					{ validator: doubleValidate, trigger: "blur" }
				],
				noApportionedArea: [
					{ required: false, message: "请输入不分摊面积", trigger: "blur" },
					{ validator: doubleValidate, trigger: "blur" }
				],
				buildPrice: [
					{ required: false, message: "请输入建构价款", trigger: "blur" },
					{ validator: doubleValidate, trigger: "blur" }
				],
				obligee: [
					{ required: true, message: "请输入权利人", trigger: "blur" },
					{ min: 0, max: 30, message: "长度在0-30个字符串", trigger: "blur" }
				],
				ownershipNature: [
					{ required: true, message: "请选择权利性质", trigger: "blur" }
				],
				endTime: [
					{ required: true, message: "请选择竣工日期", trigger: "blur" }
				],
				propertySource: [
					{ required: true, message: "请选择物业来源", trigger: "blur" }
				],
				mapCoordinates: [
					{ required: false, message: "请输入地图坐标", trigger: "blur" },
					{ min: 0, max: 30, message: "长度在0-30个字符串", trigger: "blur" },
					{ validator: mapVerification, trigger: "blur" }
				],
				projectType: [
					{ required: true, message: "请输入物业类型", trigger: "blur" },
					{ min: 0, max: 30, message: "长度在0-30个字符串", trigger: "blur" }
				],
				projectSubclassType: [
					{ required: true, message: "请输入物业用途", trigger: "blur" },
					{ min: 0, max: 30, message: "长度在0-30个字符串", trigger: "blur" }
				],
				transferMode: [
					{ required: true, message: "请输入移交方式", trigger: "blur" },
					{ min: 0, max: 30, message: "长度在0-30个字符串", trigger: "blur" }
				]
			},
			//hxf-0831-新增标识
			isEdit: "",
			isAdd: true,
			milestoneSort: "1",
			milestoneSortIndex: 0,
			// hxf-0910-文件上传
			httpRequestData: {},
			url: "/admin/sys-file/upLodeFileAdd",
			busId: "",
			modelType: "milestone",
			httpRequestFileLis: [],
			isUpload: [],
			isThereAMilestone: "",
			projectId: "",
			activeIndex: 0,
			selected: "",
			addSource: true,
			dialogVisible: false,
			dialogVisibleView: false,
			// 预览弹窗展示的类型
			previewType: "",
			// 预览文件的地址
			previewUrl: "",
			// stage: '',
			bulletInformation: {
				propertyName: "",
				facilitiesId: "",
				usedName: "",
				address: "",
				initialType: "",
				planUse: "",
				parkingSpotNum: "",
				totalBuildings: "",
				useLandArea: "",
				floorSpace: "",
				buildArea: "",
				insideArea: "",
				operation: "20",
				useArea: "",
				unmanagedArea: "",
				managedArea: "",
				noApportionedArea: "",
				buildPrice: "",
				obligee: "",
				ownershipNature: "",
				endTime: "",
				propertySource: "",
				mapCoordinates: "",
				projectType: "", //物业类型 jiaj
				projectSubclassType: "", //物业用途 jiaj
				transferType: "", //移交方式 jiaj
				transferUnit: "", //移交单位 jiaj
				receiveTime: "", //移交时间 jiaj
				transferDesc: "", //移交描述 jiaj
				remarks: ""
			},
			bulletInformationFlag: true,
			bulletInformationIndex: 0,
			planUses: [],
			initialTypes: [],
			ownershipNatureTypes: [],
			landUses: [],
			communityNameStreet: [],
			propertyUseTypes: [],
			propertyTypes: [],
			propertyUseTypesFilter: [],
			operations: []
		};
	},
	mounted() {
		this.propertyTypes = this.getDict("property_types");
		this.operations = this.getDict("property_operations");
		this.propertyUseTypes = this.getDict("property_use_types");
		this.isEdit = this.$route.query.isEdit;
		this.handleGetPlanproject();
		if (!this.isEdit) {
			let obj = {
				tempId: this.formPlanning.propertyBasic.isUpdate,
				projectId: ""
			};
			this.handleClickToUpdateItem(obj);
			// hxf-0910-tab选中项
			this.handleClick({ index: 0 }, null);
		}
	},
	computed: {
		...mapState({
			projectType: state => {
				let data = state.dict.find(item => item.type === "project_types") || {};
				let list = data.children || [];
				return data.children || [];
			},
			projectStreet: state => {
				let data = state.dict.find(item => item.type === "streets") || {};
				let list = data.children || [];
				return data.children || [];
			},
			transferModeOption: state => {
				let data =
					state.dict.find(item => item.type === "transfer_types") || {};
				return data.children || [];
			},
			communityNames: state => {
				let data =
					state.dict.find(item => item.type === "community_names") || {};
				return data.children || [];
			},
			propertySources: state => {
				let data =
					state.dict.find(item => item.type === "property_source") || {};
				return data.children || [];
			},
			manageUnits: state => {
				let data =
					state.dict.find(item => item.type === "administrative_office") || {};
				return data.children || [];
			}
		}),
		...mapGetters({
			cityAssembly: "getCityAssembly",
			districtCollection: "getDistrictCollection"
		})
	},
	mixins: [BaseLoad],
	watch: {
		"formPlanning.propertyBasic.isUpdate": function() {
			// this.formPlanning.projectMilestones.map((item, index) => {
			if (this.isThereAMilestone === this.formPlanning.propertyBasic.isUpdate) {
				let obj = {
					tempId: this.formPlanning.propertyBasic.isUpdate,
					projectId: this.projectId
				};
				if (this.addSource === true) {
					this.handleClickToUpdateItem(obj);
				}
			} else {
				let obj = {
					tempId: this.formPlanning.propertyBasic.isUpdate,
					projectId: ""
				};
				if (this.addSource === true) {
					this.handleClickToUpdateItem(obj);
				}
			}
			// })
		},
		"formPlanning.projectMilestones": {
			deep: true,
			handler(val) {
				let index = val.findIndex(item => {
					return item.materialsFormVoList.some(
						it => it.isRequired !== "0" && !it.fileBusId
					);
				});
				if (index === -1) {
					this.activeIndex = val.length - 1;
				} else {
					this.activeIndex = index;
				}
				if (val) {
					this.formPlanning.propertyBasic.stage =
						val[this.activeIndex].milestoneName;
				}

				// hxf-0915-里程碑一级文件上传后带到二级文件显示
				let flieBusId = "",
					original = "",
					flieBus = "",
					origin = "";
				val.map(item => {
					item.materialsFormVoList.forEach(
						it => {
							this.$nextTick(() => {
								//如果当前材料是复用上一级且当前里程碑不是第一个
								if (it.isReuse !== "0" && index > 0) {
									//    从上级里程碑信息中查询该材料清单名称的信息
									let mater = val[index - 1];
									if (mater && mater.materialsFormVoList instanceof Array) {
										let find = mater.materialsFormVoList.find(
											f => f.materialsName == it.materialsName
										);
										if (find) {
											//查询到了，这将查询到的材料清单的文件赋值给当前材料清单
											it.fileBusId = find.fileBusId;
											it.original = find.original;
										}
									}
								}
							});
						}
						// item.materialsFormVoList.some(it => {
						//     if (it.fileBusId !== null && it.fileBusId !== '' && it.fileBusId !== undefined) {
						//         if (it.sort === 1) {
						//             flieBusId = item.materialsFormVoList[0].fileBusId
						//             original = item.materialsFormVoList[0].original
						//         } else {
						//             flieBus = item.materialsFormVoList[1].fileBusId
						//             origin = item.materialsFormVoList[1].original
						//         }
						//     }
						//     this.$nextTick(() => {
						//         if (it.isReuse !== '0') {
						//             if (it.sort === 1) {
						//                 if (this.isUpload[it.sort - 1] === false) {
						//                     it.fileBusId = (flieBusId !== null) ? flieBusId : it.fileBusId
						//                     it.original = (original !== null) ? original : it.original
						//                 } else {
						//                     it.fileBusId = ''
						//                     it.original = ''
						//                 }
						//             } else {
						//                 if (this.isUpload[it.sort - 1] === false) {
						//                     it.fileBusId = (flieBus !== null) ? flieBus : it.fileBusId
						//                     it.original = (origin !== null) ? origin : it.original
						//                 } else {
						//                     it.fileBusId = ''
						//                     it.original = ''
						//                 }
						//             }
						//         }
						//     })
						// }
					);
				});
			}
		}
	},
	created() {
		if (this.$route.meta.title !== "新增") {
			this.isAdd = false;
		}
		// console.log(this.$route.meta.title);
		this.planUses = this.getDict("plan_uses");
		this.initialTypes = this.getDict("project_init_type");
		this.ownershipNatureTypes = this.getDict("asset-ownership-nature");
		this.landUses = this.getDict("land_uses");
		// if (this.ownershipNatureTypes.length > 0 && this.ownershipNatureTypes !== null) {
		//     for (let i = 0; i < this.ownershipNatureTypes.length; i++) {
		//         this.ownershipNatureTypes[i].value = parseInt(this.ownershipNatureTypes[i].value)
		//     }
		// }
		this.formPlanning.landInfo.cityCode = this.cityAssembly[0].value;
		this.formPlanning.landInfo.countyCode = this.districtCollection[0].value;
	},
	methods: {
		//jiaj 根据物业类型，获取对应的物业用途
		changeProjectType(val) {
			//重置物业用途
			this.propertyUseTypesFilter = [];
			if (val) {
				this.bulletInformation.projectSubclassType = "";
				//过滤物业用途
				this.propertyUseTypesFilter = this.propertyUseTypes.filter(
					ut => ut.value.indexOf(val) == 0
				);
			}
		},

		// hxf-0828-配套信息删除
		handleClickDelete(index, rows) {
			rows.splice(index, 1);
		},
		// hxf-0828-更新
		handleUpdate() {
			// this.formPlanning.supportingFacilities.map((item, index) => {
			//     this.$set(this.formPlanning.supportingFacilities[index], 'endTime',this.dataFormat(null,null,this.formPlanning.supportingFacilities[index].endTime) )
			// })
			this.formPlanning.landInfo.areaCode =
				this.formPlanning.landInfo.cityCode +
				"-" +
				this.formPlanning.landInfo.countyCode;
			this.formPlanning.landInfo.address =
				this.getCardTypeValue(
					this.formPlanning.landInfo.cityCode,
					this.cityAssembly
				) +
				this.getCardTypeValue(
					this.formPlanning.landInfo.countyCode,
					this.districtCollection
				) +
				this.getCardTypeValue(
					this.formPlanning.landInfo.street,
					this.projectStreet
				) +
				this.getCardTypeValue(
					this.formPlanning.landInfo.community,
					this.communityNames
				);

			//赋值坐标以及管理权属
			this.formPlanning.mapCoordinates = this.formPlanning.propertyBasic.mapCoordinates;
			this.formPlanning.manageUnit = this.formPlanning.propertyBasic.manageUnit;

			this.$refs["formConstructionLand"].validate(valid => {
				if (valid) {
					this.$refs["formConstruction"].validate(valid => {
						if (valid) {
							// if (this.formPlanning.projectMilestones[this.formPlanning.projectMilestones.length - 1].materialsFormVoList.some(it =>
							//     it.isRequired !== '0' && !it.fileBusId))return this.$message.error('请上传必填文件！')
							if (
								this.formPlanning.projectMilestones[
									this.selected
								].materialsFormVoList.some(
									it => it.isRequired !== "0" && !it.fileBusId
								)
							)
								return this.$message.error("请上传必填文件！");
							this.formPlanning.propertyBasic.projectId = this.isEdit;

							let areaCode =
								this.formPlanning.landInfo.cityCode +
								"-" +
								this.formPlanning.landInfo.countyCode +
								"-" +
								this.formPlanning.landInfo.street +
								"-" +
								this.formPlanning.landInfo.community;
							//判断项目名称+地址是否存在
							validateProject({
								addressInfo: this.formPlanning.landInfo.addressInfo,
								areaCode: areaCode,
								propertyName: this.formPlanning.propertyBasic.projectName,
								projectId: this.projectId
							}).then(res => {
								if (res.data.data === 1) {
									this.$message.error("该地址下的项目名称已存在，请重新输入！");
								} else {
									this.loadAction("保存中");
									underconstructionEdit(this.formPlanning)
										.then(res => {
											this.loadClose();
											this.$message.success("保存成功！");
											this.closeNowRouter();
										})
										.catch(e => {
											console.log(e);
											this.loadClose();
											this.$message.error("保存失败");
										});
								}
							});

							// underconstructionEdit(this.formPlanning).then(res => {
							//     this.$message({
							//         message: '更新成功！',
							//         type: 'success'
							//     })
							//     this.closeNowRouter();
							// })
						} else {
							this.$message.error("保存失败！");
							return false;
						}
					});
				} else {
					this.$message.error("保存失败！");
					return false;
				}
			});
		},
		// hxf-0828-保存
		handlePreservation() {
			// this.formPlanning.supportingFacilities.map((item, index) => {
			//     this.$set(this.formPlanning.supportingFacilities[index], 'endTime',this.dataFormat(null,null,this.formPlanning.supportingFacilities[index].endTime) )
			// })
			this.formPlanning.landInfo.areaCode =
				this.formPlanning.landInfo.cityCode +
				"-" +
				this.formPlanning.landInfo.countyCode;
			this.formPlanning.landInfo.address =
				this.getCardTypeValue(
					this.formPlanning.landInfo.cityCode,
					this.cityAssembly
				) +
				this.getCardTypeValue(
					this.formPlanning.landInfo.countyCode,
					this.districtCollection
				) +
				this.getCardTypeValue(
					this.formPlanning.landInfo.street,
					this.projectStreet
				) +
				this.getCardTypeValue(
					this.formPlanning.landInfo.community,
					this.communityNames
				);

			//赋值坐标以及管理权属
			this.formPlanning.mapCoordinates = this.formPlanning.propertyBasic.mapCoordinates;
			this.formPlanning.manageUnit = this.formPlanning.propertyBasic.manageUnit;

			const formConstructionLand = new Promise((resolve, reject) => {
				this.$refs["formConstructionLand"].validate(valid => {
					if (valid) resolve();
				});
			});
			const formConstruction = new Promise((resolve, reject) => {
				this.$refs["formConstruction"].validate(valid => {
					if (valid) resolve();
				});
			});

			Promise.all([formConstructionLand, formConstruction]).then(() => {
				//文件上传
				if (
					this.formPlanning.projectMilestones[
						this.selected
					].materialsFormVoList.some(
						it => it.isRequired !== "0" && !it.fileBusId
					)
				)
					return this.$message.error("请上传必填文件！");

				let areaCode =
					this.formPlanning.landInfo.cityCode +
					"-" +
					this.formPlanning.landInfo.countyCode +
					"-" +
					this.formPlanning.landInfo.street +
					"-" +
					this.formPlanning.landInfo.community;

				validateProject({
					addressInfo: this.formPlanning.landInfo.addressInfo,
					areaCode: areaCode,
					propertyName: this.formPlanning.propertyBasic.projectName
				}).then(res => {
					if (res.data.data === 1) {
						this.$message.error("该地址下的项目名称已存在，请重新输入！");
					} else {
						this.loadAction("保存中");
						underconstructionAdd(this.formPlanning)
							.then(res => {
								this.loadClose();
								this.$message.success("保存成功！");
								this.closeNowRouter();
							})
							.catch(e => {
								console.log(e);
								this.loadClose();
								this.$message.error("保存失败");
							});
					}
				});
			});

			// this.$refs['formConstructionLand'].validate((valid) => {
			//     if (valid) {
			//         this.$refs['formConstruction'].validate((valid) => {
			//             if (valid) {
			//                 // if (this.formPlanning.projectMilestones[this.formPlanning.projectMilestones.length - 1].materialsFormVoList.some(it =>
			//                 //     it.isRequired !== '0' && !it.fileBusId))return this.$message.error('请上传必填文件！')
			//
			//             } else {
			//                 this.$message.error('保存失败！')
			//                 return false;
			//             }
			//         })
			//     }else{
			//         this.$message.error('保存失败！')
			//         return false;
			//     }
			// })
		},
		closeNowRouter() {
			//关闭当前新增页，暂时没找到好办法
			this.$store.commit("delHistoryRoute", this.$route.fullPath);
			// this.$parent.$children[2].closeTab('current')
			//跳转
			this.$router.push(
				"/property-plan-manage/projects-under-construction/index"
			);
		},
		// hxf-0901-验证项目编号是否存在
		projectCodeOnly(value, callback) {
			validateprojectCode({
				projectCode: value,
				projectId: this.isEdit || ""
			}).then(res => {
				if (res.data.data === 0) {
					return callback();
				} else {
					return callback(new Error("项目编号已存在，请重新输入！"));
				}
			});
		},
		// hxf-0901-回显
		handleGetPlanproject() {
			if (this.isEdit) {
				getUnderconstruction(this.isEdit).then(res => {
					if (res.data.code === 0) {
						this.formPlanning = res.data.data;

						//赋值坐标以及管理权属
						this.$set(
							this.formPlanning.propertyBasic,
							"manageUnit",
							this.formPlanning.manageUnit
						);
						this.$set(
							this.formPlanning.propertyBasic,
							"mapCoordinates",
							this.formPlanning.mapCoordinates
						);

						// this.stage = this.formPlanning.propertyBasic.stage
						if (this.formPlanning.propertyBasic.addSource === "1") {
							this.addSource = false;
						}
						if (this.formPlanning.projectMilestones.length > 0) {
							this.milestoneSortIndex = this.formPlanning.projectMilestones.findIndex(
								pm => pm.milestoneName == this.formPlanning.propertyBasic.stage
							);
							if (this.milestoneSortIndex == -1) {
								this.milestoneSortIndex = 0;
							}
							this.milestoneSort = (this.milestoneSortIndex + 1).toString();
						}
						// this.$set(this.formPlanning.propertyBasic,'projectAddr',res.data.data.projectAddr)
						this.handleClick({ index: this.milestoneSortIndex }, null);
						let materialsNameRequired = `<span style="color: #f66c6c">*</span>`;
						this.formPlanning.projectMilestones.map(item => {
							item.materialsFormVoList.map(i => {
								if (i.isRequired === "1") {
									i.materialsName += materialsNameRequired;
								}
							});
						});
						this.$forceUpdate();
						this.isThereAMilestone = res.data.data.propertyBasic.isUpdate;
						this.projectId = res.data.data.propertyBasic.projectId;
						this.initCommunityName();
					}
				});
			}
		},
		/*// hxf-0902-添加
        superInforAdd() {
            this.formPlanning.supportingFacilities.push({
                realtyName: '',
                projectType: '',
                projectSubclassType: '',
                floorSpace: '',
                floorArea: '',
                transferMode: '',
                remarks: '',
                newAdd: true,
            })
        },*/
		// hxf-0929-添加(改)
		superInforAdd() {
			this.dialogVisible = true;
			// for(let i in this.bulletInformation) {
			//     this.bulletInformation[i] = ''
			// }

			//还原的
			(this.bulletInformation = {
				buildingName: "", //楼栋名称 jiaj
				floorNum: "", //楼层号 jiaj
				propertyName: "",
				usedName: "",
				address: "",
				initialType: "",
				parkingSpotNum: "",
				floorSpace: "",
				buildArea: "",
				insideArea: "",
				operation: "20",
				unmanagedArea: "",
				managedArea: "",
				noApportionedArea: "",
				projectType: "", //物业类型 jiaj
				projectSubclassType: "", //物业用途 jiaj
				transferType: "", //移交方式 jiaj
				transferUnit: "", //移交单位 jiaj
				receiveTime: "", //移交时间 jiaj
				transferDesc: "", //移交描述 jiaj
				remarks: ""
			}),
				(this.bulletInformationFlag = true);
			this.bulletInformationIndex = 0;
		},
		/*// hxf-0902-配套信息编辑
        handleClickEdit(row) {
            this.$set(row, 'newAdd', true)
            this.$forceUpdate()
        },*/
		// hxf-0929-配套信息编辑（改）
		handleClickEdit(scope) {
			this.dialogVisible = true;
			this.bulletInformation = scope.row;
			this.bulletInformationFlag = false;
			this.bulletInformationIndex = scope.$index;
			this.propertyUseTypesFilter = this.propertyUseTypes.filter(
				ut => ut.value.indexOf(this.bulletInformation.projectType) == 0
			);
		},
		handleUnitConstractionArea() {
			if (this.bulletInformation.buildArea) {
				if (
					Number(this.bulletInformation.insideArea) >
					Number(this.bulletInformation.buildArea)
				) {
					this.$message.error("套内面积不能大于建筑面积！");
					this.bulletInformation.insideArea = "";
				}
			}
		},
		// hxf-0929-弹框取消
		handleDialogClear() {
			this.dialogVisible = false;
			// for(let i in this.bulletInformation) {
			//     this.bulletInformation[i] = ''
			// }

			//还原的
			this.bulletInformation = {};
		},
		// hxf-0929-弹框确认
		handleDialogClick() {
			this.$refs["bulletInformation-form"].validate(valid => {
				if (valid) {
					if (this.bulletInformationFlag) {
						this.formPlanning.supportingFacilities.push(this.bulletInformation);
						this.handleDialogClear();
					} else {
						this.formPlanning.supportingFacilities[
							this.bulletInformationIndex
						] = this.bulletInformation;
						this.handleDialogClear();
					}
				} else {
					this.$message.error("保存失败！");
					return false;
				}
			});
		},
		// hxf-0910-tab选中项
		handleClick(tab, event) {
			this.isUpload = [];
			this.selected = tab.index;
			// 如果文件busid为空那么就可以上传
			if (this.formPlanning.projectMilestones[tab.index]) {
				this.formPlanning.projectMilestones[tab.index].materialsFormVoList.map(
					(item, index) => {
						if (
							item.fileBusId === null ||
							item.fileBusId === "" ||
							item.fileBusId === undefined
						) {
							this.isUpload.push(true);
						} else if (item.isReuse === "1") {
							this.isUpload.push(false);
						} else {
							this.isUpload.push(false);
						}
					}
				);
			} else {
				this.isUpload.push(true);
			}
		},
		// hxf-0910-文件上传
		httpRequest(params, row) {
			try {
				if (params.file.size > 10 * 1024 * 1024) {
					this.$message({
						type: "error",
						message: `上传文件大小不能超过 10MB!`
					});
					return;
				}
				let format = [
					"jpg",
					"jpeg",
					"png",
					"gif",
					"bmp",
					"wmv",
					"mpeg",
					"mp4",
					"doc",
					"docx",
					"xls",
					"xlsx",
					"ppt",
					"pptx",
					"txt",
					"pdf"
				];
				let formatType = params.file.name.split(".")[1];
				if (format.indexOf(formatType) === -1) {
					this.$message.error(
						"文件上传不支持该格式文件，目前仅支持'jpg,jpeg,png,gif,bmp,wmv,mpeg,mp4,doc,docx,xls,xlsx,ppt,pptx,txt,pdf'格式文件！"
					);
					return;
				}
				//  hxf-0910-用FormData存放上传文件
				let formData = new FormData();
				formData.append("file", params.file);
				formData.append("module", this.modelType);
				if (this.busId) {
					formData.append("busId", busId);
				}
				this.http.post(this.url, formData).then(resp => {
					if (resp.data.code === 0) {
						row.row.original = params.file.name;
						row.row.fileBusId = resp.data.data;
						this.isUpload[row.$index] = false;
					} else {
						this.$message.error("文件上传失败！");
					}
				});
			} catch (e) {
				console.log(e);
			}
		},
		// hxf-0910-是否为默认项目，默认选择否
		handleClickToUpdateItem(obj) {
			initMilestones(obj).then(res => {
				if (res.data.code === 0) {
					this.formPlanning.projectMilestones = res.data.data;
					let materialsNameRequired = `<span style="color: #f66c6c">*</span>`;
					this.formPlanning.projectMilestones.map(item => {
						item.materialsFormVoList.map(i => {
							if (i.isRequired === "1") {
								i.materialsName += materialsNameRequired;
							}
						});
					});
					// 新增回显初始化加载自动点击tabs第一个
					this.handleClick({ index: 0 }, null);
					this.$forceUpdate();
				} else {
					this.$message.error("未获取到里程碑信息！");
				}
			});
		},
		// hxf-0910-多选选择方法
		handleSelectionChange(val) {
			this.multipleSelection = val;
		},
		// hxf-0911-移除文件
		triggerBeforeRemove(item) {
			this.beforeRemove(item);
		},
		beforeRemove(file) {
			this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning"
			})
				.then(() => {
					delFiles(file.row.fileBusId, this.modelType).then(resp => {
						if (resp.data.code === 0) {
							this.$message({
								type: "success",
								message: "删除成功!"
							});
							file.row.original = "";
							file.row.fileBusId = "";
							this.isUpload[file.$index] = true;
						} else {
							this.$message({
								type: "error",
								message: "删除失败!"
							});
						}
					});
				})
				.catch(() => {
					this.$message({
						type: "info",
						message: "已取消删除"
					});
				});
		},
		// PDF预览\文件下载
		triggerBeforeDownload(item) {
			if (item.row.fileId === null) {
				this.$message.warning("文件暂未上传到服务器，无法下载！");
			} else {
				if (item.row.original.split(".")[1] === "pdf") {
					checkFiles(item.row.fileId).then(res => {
						if (res.data.code === 0) {
							this.previewType = "pdf";
							this.previewUrl = item.row.fileId;
							this.dialogVisibleView = true;
						} else {
							this.$message.warning("文件不存在或已删除！");
						}
					});
				} else if (
					item.row.original.split(".")[1] === "jpg" ||
					item.row.original.split(".")[1] === "png" ||
					item.row.original.split(".")[1] === "jpeg"
				) {
					checkFiles(item.row.fileId).then(res => {
						if (res.data.code === 0) {
							this.previewType = "image";
							this.previewUrl = "/admin/sys-file/img/" + item.row.fileId;
							this.dialogVisibleView = true;
						} else {
							this.$message.warning("文件不存在或已删除！");
						}
					});
				} else {
					checkFiles(item.row.fileId).then(res => {
						if (res.data.code === 0) {
							download(
								"/admin/sys-file/download/" + item.row.fileId,
								this.modelType
							).then(response => {
								downloadBlob(response.data, item.row.original);
							});
						} else {
							this.$message.warning("文件不存在或已删除！");
						}
					});
				}
			}
		},
		// hxf-0914-建筑面积失焦校验
		handleFloorAreaBlur(row) {
			if (Number(row.floorArea) < Number(row.floorSpace)) {
				this.$message.error("建筑面积不能小于占地面积！");
				row.floorArea = "";
			}
		},
		handleFloorSpaceBlur(row) {
			if (row.floorArea !== "") {
				if (Number(row.floorArea) < Number(row.floorSpace)) {
					this.$message.error("占地面积不能大于建筑面积！");
					row.floorSpace = "";
				}
			}
		},
		dataFormat: function(row, column, cellValue) {
			if (!cellValue) {
				return "";
			}
			return moment(cellValue).format("YYYY-MM-DD");
		},
		getCardTypeValue(num, sum) {
			let arr = sum.filter(e => e.value === num);
			if (arr.length > 0) {
				return arr[0].label;
			} else {
				return num;
			}
		},
		// 监听地图坐标监听
		resetPosition(data) {
			let position = JSON.parse(data);
			if (position.length) {
				this.formPlanning.propertyBasic = {
					...this.formPlanning.propertyBasic,
					mapCoordinates: position.join(",")
				};

				//this.propForm.propertyBasicInfo.mapCoordinates = position.join(',')
			}
		},
		// hxf-1009-区改变清空街道和社区
		handleChangeCountyCode() {
			this.formPlanning.landInfo.street = "";
			this.formPlanning.landInfo.community = "";
			this.formPlanning.landInfo.addressInfo = "";
		},
		// hxf-1009-街道改变清空社区
		handleChangeStreet() {
			this.formPlanning.landInfo.community = "";
			this.formPlanning.landInfo.addressInfo = "";
			this.initCommunityName();
		},
		handleChangeCommunity() {
			this.formPlanning.landInfo.addressInfo = "";
		},
		initCommunityName() {
			this.communityNameStreet.length = 0;
			let selectStreet = this.formPlanning.landInfo.street;
			if (
				selectStreet != "" &&
				this.communityNames != null &&
				this.communityNames.length > 0
			) {
				this.communityNameStreet = this.communityNames.filter(
					cn => cn.value.indexOf(selectStreet) != -1
				);
			}
		},
		handleValidateProject(value) {
			if (
				this.formPlanning.landInfo.cityCode === "" ||
				this.formPlanning.landInfo.countyCode === "" ||
				this.formPlanning.landInfo.street === "" ||
				this.formPlanning.landInfo.community === ""
			) {
				this.$message.error("请将市区街道社区填写完整后再填写详细地址！");
				this.formPlanning.landInfo.addressInfo = "";
			} else {
				let areaCode =
					this.formPlanning.landInfo.cityCode +
					"-" +
					this.formPlanning.landInfo.countyCode +
					"-" +
					this.formPlanning.landInfo.street +
					"-" +
					this.formPlanning.landInfo.community;
				validateProject({ addressInfo: value, areaCode: areaCode }).then(
					res => {
						if (res.data.data === 2) {
							this.$message.warning("该地址已存在！");
						}
					}
				);
			}
		},
		// 验证宗地号是否存在
		landCodeOnly(value) {
			validateLandCode({
				landCode: value,
				landId: this.formPlanning.landInfo.landId || ""
			}).then(res => {
				if (res.data.data !== 0) {
					this.$message.warning("宗地号已存在，请确认是否继续操作");
				}
			});
		},
		//验证物业名称唯一
		propertyNameOnly(value) {
			validateFacRoomName({
				roomName: value,
				facId: this.bulletInformation.facilitiesId || ""
			}).then(res => {
				if (res.data.data !== 0) {
					this.$message.error("物业名称已存在，请重新输入！");
					this.bulletInformation.propertyName = "";
				}
			});
		},
		// 经营面积失焦校验
		handleAreaCompared() {
			if (
				Number(this.bulletInformation.unmanagedArea) +
					Number(this.bulletInformation.managedArea) >
				Number(this.bulletInformation.buildArea)
			) {
				this.$message.error("经营面积+非经营面积之和不能大于建筑面积！");
				this.bulletInformation.managedArea = "";
			}
		},
		//分摊共用面积
		handleNoAppor() {
			if (
				Number(this.bulletInformation.noApportionedArea) >
				Number(this.bulletInformation.buildArea)
			) {
				this.$message.error("分摊公用面积不能大于建筑面积！");
				this.bulletInformation.noApportionedArea = "";
			}
		},
		validateProjectCountryCode(value) {
			validateProjectCountryCode(value, this.projectId || "").then(res => {
				if (res.data.data !== 0) {
					this.$message.error("项目国家编码已存在，请重新输入");
					this.formPlanning.propertyBasic.projectCountryCode = "";
				}
			});
		}
	},
	filters: {
		ellipsis(value) {
			if (!value) {
				return "";
			} else if (value.length > 6) {
				return value.slice(0, 6) + "...";
			} else {
				return value;
			}
		}
	}
};
